package com.example.repository;

import com.example.model.Inventory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface InventoryRepository extends JpaRepository<Inventory, Long> {
    
    // 根据物品代码查找
    Optional<Inventory> findByItemCode(String itemCode);
    
    // 根据分类查找
    List<Inventory> findByCategory(Inventory.ItemCategory category);
    
    // 分页查找库存
    Page<Inventory> findByCategory(Inventory.ItemCategory category, Pageable pageable);
    
    // 查找库存不足的物品
    @Query("SELECT i FROM Inventory i WHERE i.currentStock <= i.minStock")
    List<Inventory> findLowStockItems();
    
    // 查找即将过期的物品
    @Query("SELECT i FROM Inventory i WHERE i.expiryDate IS NOT NULL AND i.expiryDate <= :date")
    List<Inventory> findExpiringItems(LocalDateTime date);
    
    // 根据名称模糊查找
    @Query("SELECT i FROM Inventory i WHERE i.itemName LIKE %:name%")
    List<Inventory> findByItemNameContaining(String name);
    
    // 统计各分类库存数量
    @Query("SELECT i.category, COUNT(i) FROM Inventory i GROUP BY i.category")
    List<Object[]> countByCategory();
    
    // 统计库存总价值
    @Query("SELECT COALESCE(SUM(i.totalValue), 0) FROM Inventory i")
    Double getTotalInventoryValue();
    
    // 统计低库存物品数量
    @Query("SELECT COUNT(i) FROM Inventory i WHERE i.currentStock <= i.minStock")
    Long countLowStockItems();
}
